What is the difference between new() and make() in GoLang

What is the difference between new() and make() in GoLang

Hi, this is Charu from Classmethod. In this blog, we will be talking about new() and make() functions in go. They have very small difference but great impact. So, it is important to know their usecases.

Let's get started!

new()

The new() function is a built-in function in Go. It allocates memory for a new object and returns a pointer to it. Unlike constructors in object-oriented languages, new() doesn't initialize the fields of a struct. Instead, it returns a pointer to a zeroed value of the specified type.

It is primarily used for initializing and obtaining a pointer to a newly allocated zeroed value of a given type, usually for data types like structs.

package main

import "fmt"

type Point struct {
    x, y int
}

func main() {
    // Creating a new instance of Point using new()
    p := new(Point)
    
    // Accessing fields of the Point struct
    p.x = 5
    p.y = 10

    fmt.Println("Point:", p)
}

In the above example, new() is used to allocate memory to a Point() object. It's essential to remember that new() is primarily used for creating pointers to struct types.

make():

On the other hand, make() is used to create slices, maps, and channels - data structures that require runtime initialization, rather than struct instances. Unlike new(), it initializes and allocates memory for these data structures, returning an initialized (not zeroed) value of the specified type.

package main

import "fmt"

func main() {
    // Creating a slice of integers using make()
    slice := make([]int, 5)
    
    // Populating the slice with values
    for i := 0; i < len(slice); i++ {
        slice[i] = i * 2
    }

    fmt.Println("Slice:", slice)
}

In the above example, we are using make() to initialize a slice with a length of 5. We are then putting values in that slice using a for loop. It's worth noting that make() is exclusively used for creating slices, maps, and channels.

Which one to choose?

Now, to summarize:

new() for Structs: When you need to allocate memory for a new instance of a struct, new() is your go-to choice. Remember that new() returns a pointer to a zeroed value of the specified type, so you'll need to initialize its fields manually.

make() for Slices, Maps, and Channels: For dynamic data structures like slices, maps, and channels, make() is the preferred option. It not only allocates memory but also initializes the data structure, readying it for immediate use.

Thank you for reading!

Happy Learning:)

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.